package com.ler.yrmall.member.rpc;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ler.yrmall.member.entity.MemberEntity;
import com.ler.yrmall.member.entity.MemberReceiveAddressEntity;
import com.ler.yrmall.member.service.MemberReceiveAddressService;
import com.ler.yrmall.member.service.MemberService;
import com.ler.yrmall.utils.SecurityUtils;
import com.ler.yrmall.member.api.MemberApi;
import com.ler.yrmall.member.dto.MemberDTO;
import com.ler.yrmall.member.dto.MemberReceiveAddressDTO;
import com.ler.yrmall.basic.Result;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Leron
 * @version 1.0
 */
@Service
@DubboService
public class MemberApiImpl implements MemberApi {

    @Resource
    private MemberService memberService;

    @Resource
    private MemberReceiveAddressService receiveAddressService;


    @Override
    public Result<MemberDTO> getMemberByUsername(String username) {
        MemberEntity member = memberService.getMemberByUserName(username);
        MemberDTO target = new MemberDTO();
        BeanUtils.copyProperties(member, target);
        return Result.ok(target);
    }

    @Override
    public Result<MemberReceiveAddressDTO> getMemberAddress(long addressId) {
        MemberReceiveAddressEntity address = receiveAddressService.getById(addressId);
        MemberReceiveAddressDTO target = new MemberReceiveAddressDTO();
        BeanUtils.copyProperties(address, target);
        return Result.ok(target);
    }

    @Override
    public Result<List<MemberReceiveAddressDTO>> getAddressList() {
        Long userId = SecurityUtils.getLoginUser().getId();
        List<MemberReceiveAddressDTO> collect = receiveAddressService
                .list(Wrappers.<MemberReceiveAddressEntity>lambdaQuery().eq(MemberReceiveAddressEntity::getMemberId, userId))
                .stream()
                .map(item -> {
                    MemberReceiveAddressDTO target = new MemberReceiveAddressDTO();
                    BeanUtils.copyProperties(item, target);
                    return target;
                }).collect(Collectors.toList());
        return Result.ok(collect);
    }

    @Override
    public Result<MemberReceiveAddressDTO> getDefaultAddress() {
        return Result.ok(BeanUtil.copyProperties(receiveAddressService.defaultAddress(),MemberReceiveAddressDTO.class));
    }

    @Override
    public Long getMemberCount() {
        return memberService.count();
    }
}
